<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="filter">
          <el-form-item label="文章分类">
            <el-select v-model="filter.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="filter.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="search">筛选</el-button>
            <el-button type="info" size="small" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="openDialog('add')">发表文章</el-button>
      </div>
       <!-- 文章表格区域 -->
        <el-table :data="artList" style="width: 100%;" border stripe>
            <el-table-column label="文章标题" prop="title">
            </el-table-column>
            <el-table-column label="分类" prop="cate_name"></el-table-column>
            <el-table-column label="发表时间" >
                <template v-slot ="scope">
                    {{formatDate(scope.row.pub_date)}}
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="state"></el-table-column>
            <el-table-column label="操作">
                <template v-slot="scope">
                    <el-button type="primary" size="mini" @click="openDialog('edit',scope.row.id)">修改</el-button>
                    <el-button type="danger" size="mini" @click="del(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
       <!-- 分页区域 -->
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
    </el-card>

     <el-dialog
    :title="dialogTitle"
    :visible.sync="addArtVisible"
    fullscreen
     @closed="onClosed"
    :before-close="handleClose"
    >
     <!-- 发布文章的对话框 -->
    <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
    <el-form-item label="文章标题" prop="title">
        <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
    </el-form-item>
    <el-form-item label="文章分类" prop="cate_id">
        <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
        <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
        <!-- <el-option label="区域二" value="beijing"></el-option> -->
        </el-select>
    </el-form-item>
    <el-form-item label="文章内容" prop="content">
    <!-- 使用 v-model 进行双向的数据绑定 -->
      <quill-editor v-model="pubForm.content" @blur="$refs.pubFormRef.validateField('content')"></quill-editor>
    </el-form-item>
    <el-form-item label="文章封面" prop="cover_img">
        <!-- 用来显示封面的图片 -->
        <img v-if="preview" :src="preview" alt="" class="cover-img" ref="imgRef" />
        <img v-else src="../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
        <br />
        <!-- 文件选择框，默认被隐藏 -->
        <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="cImage"/>
        <!-- 选择封面的按钮 -->
        <el-button type="text" @click="$refs.iptFileRef.click()">+ 选择封面</el-button>
    </el-form-item>
    <el-form-item>
        <el-button type="primary" @click="add('已发布')">发布</el-button>
        <el-button type="info" @click="add('草稿')">存为草稿</el-button>  
    </el-form-item>
    </el-form>
     </el-dialog>

     <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
        <h1 class="title">{{ artDetail.title }}</h1>

        <div class="info">
            <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
            <span>发布时间：{{ formatDate(artDetail.pub_date) }}</span>
            <span>所属分类：{{ artDetail.cate_name }}</span>
            <span>状态：{{ artDetail.state }}</span>
        </div>
            
        <!-- 分割线 -->
        <el-divider></el-divider>
        
        <!-- 文章的封面 -->
        <img :src="'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img" alt="" />

        <!-- 文章的详情 -->
        <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";
import dayjs from 'dayjs'
import {getCateList, addArticle, getArticleList, getArticleDetail, updateArticleList, delArticleList } from '@/api/article'
export default {
  name: 'ArtList',
  components: {
    quillEditor
  },
  data() {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      addArtVisible:false,
      pubForm:{
            title:'',
            cate_id:'',
            content: '',
            cover_img:'',
        },
        putForm:{
            id: '',
            title:'',
            cate_id:'',
            content: '',
            state: '',
            cover_img:'',
        },
      pubFormRules:{
        title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章分类', trigger: 'click' }],
        content: [{ required: true, message: '请输入文字内容', trigger: 'blur' }],
       cover_img : [{ required: true, message: '请选择图片', trigger: 'change' }]
      },
      cateList:[],
      preview:'',
      state:'',
      artList:[],
      total:0,
      dialogType: '',
      filter:{
        cate_id:'',
        state:''
      },
      detailVisible:false,
      artDetail:{},
      id: 0,
      }
  },
  methods:{
    handleClose(done) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          type: 'warning'
        }).then(_ => {
            done();
          })
          .catch(_ => {});
      },
    async getArtCate(){
       const res = await getCateList()
      
    //    console.log(res);
       if(res.code !== 0) return this.$message.error(res.message)
       this.cateList =res.data
    },
    cImage(e){
       const file = e.target.files[0]
       if(file){
          this.pubForm.cover_img = file
          this.preview = URL.createObjectURL(file)
       }else{
          this.pubForm.cover_img = ''
          this.preview = ''
       }
       this.$refs.pubFormRef.validateField('cover_img')
    },
    add(state){
        this.pubForm.state = state
       this.$refs.pubFormRef.validate(async valid => {
          if(!valid)  return 
          const fd = new FormData
          for(let k in this.pubForm) {
              fd.append(k, this.pubForm[k])
          }
          if (this.dialogType === 'add') {
            const res = await addArticle(fd)
            console.log(res);
            if(res.code != 0) return this.$message.error(res.message)
            this.$message.success(res.message)
          }
          
           if (this.dialogType === 'edit') {
            const putres = await getArticleDetail(this.id)
            this.putForm = {
               id: putres.data.id,
              title: putres.data.title,
              cate_id: putres.data.cate_id,
              content: putres.data.content,
              state: putres.data.state,
              cover_img: putres.data.cover_img,
            }
            console.log(this.putForm)
            const fds = new FormData
            for(let k in this.putForm) {
              fds.append(k, this.putForm[k])
          } 
            console.log(fds)
             const res = await updateArticleList(fds)
             console.log(res);
            if(res.code != 0) return this.$message.error(res.message)
            this.$message.success(res.message)
          }
           this.addArtVisible = false
           this.getArtList()
       })
    },
    onClosed(){
        this.pubForm ={
            title:'',
            cate_id:'',
            content: '',
            cover_img:'',
        }
        this.preview = ''
    },
    async getArtList(){
        const res = await getArticleList(this.q)
          console.log(this.q)
         console.log(res);
        if(res.code != 0) return this.$message.error(res.message)
        this.artList = res.data
        this.total = res.total
    },
    formatDate(val){
        return dayjs(val).format('YYYY-MM-DD HH:mm:ss') 
    },
    handleSizeChange(size){
    this.q.pagesize = size
     this.getArtList()
    },
    handleCurrentChange(pNum){
    // 为页码值赋值
    this.q.pagenum = pNum
    // 重新发起请求
    this.getArtList()
    },
    search(){
        this.q.cate_id = this.filter.cate_id
        this.q.state = this.filter.state
        this.q.pagenum = 1
        this.getArtList()
    },
    resetSearch(){
        this.filter = {
           cate_id : '',
           state : '',
        },
        this.q = {
            state : '',
            cate_id : '',
             pagenum: 1,
              pagesize: 2
        }
   },
    // 根据 id 删除文章
    del(id) {
    // 1. 询问用户是否要删除
    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
         // 执行删除的操作
    const res = await delArticleList(id)

    if (res.code !== 0) return this.$message.error(res.message)
    this.$message.success(res.message)

    //如果 artList数组里面只要一条数据，并且不是第一页 回到上一页
    if(this.artList.length === 1  && this.q.pagenum > 1){
        this.q.pagenum--
    }
    // 刷新列表数据
    this.getArtList()
    }).catch(() => {
        this.$message({
            type:'info',
            message:'已取消删除'
        })
    })
   },
  async showDetail(id) {
    // 请求详情数据
    const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
    if (res.code !== 0) return this.$message.error('获取文章详情失败!')
    this.artDetail = res.data
    // 展示对话框
    this.detailVisible = true
    },
    async openDialog(type, id) {
      this.dialogType = type
      this.addArtVisible = true
      this.id = id
      // this.$refs.imgRef.src = '../../assets/images/cover.jpg'
      if (type !== 'add') {
        const res = await getArticleDetail(id)
        console.log(res)
        this.pubForm = {
          ...res.data
        }
        console.log(this.$refs.imgRef)
        // this.$refs.imgRef.src = `http://big-event-vue-api-t.itheima.net${res.data.cover_img}`
      }
      
    }
},
  created(){
    this.getArtCate()
    this.getArtList()
  },
  computed: {
    dialogTitle () {
      let title = '文章标题'
      if (this.dialogType === 'add') title = '发布文章'
      if (this.dialogType === 'edit') title = '修改文章'
      return title
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-editor {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 15px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}
.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
